<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model="tableForm"
      :page.sync="page"
      :search.sync="query"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @selection-change="selectionChange"
      @search-change="searchChange"
      @search-reset="searchReset"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="menuRight" slot-scope="{ row }">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft" slot-scope="{ row }">
        <el-button type="primary" plain size="small" icon="el-icon-plus" v-if="permission.testStand_add" @click="handleAdd">新增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.testStand_delete" @click="handleDel" :disabled="!selectionList.length">删除</el-button>
        <el-button type="warning" size="small" v-if="permission.testStand_export" icon="el-icon-download" @click="handleExport">导出 </el-button>
      </template>
      <template slot="menu" slot-scope="{ row }">
        <el-button v-if="permission.testStand_edit" size="small" type="text" @click="handleView(row)">详情 </el-button>
        <el-button v-if="permission.testStand_edit" :disabled="![6, 1].includes(row.status)" size="small" type="text" @click="handleEdit(row)">编辑 </el-button>
        <el-button v-if="permission.testStand_history" size="small" type="text" @click="handleViewHistory(row)">工具履历 </el-button>
        <el-button v-if="permission.testStand_disabled" size="small" type="text" @click="handleDisabled(row)" :disabled="![1, 6].includes(row.status)"
          >{{ row.status === 6 ? '启用' : '禁用' }}
        </el-button>
      </template>
    </avue-crud>
    <!--新增编辑详情弹框-->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" destroy-on-close append-to-body width="70%" top="5vh" @close="handleCancel">
      <div class="sail-header-dialog-content">
        <avue-form :option="formOption" v-model="form" ref="formRef" @submit="submitForm">
          <template slot="PICTURE">
            <div v-if="dialogTitle != '详情' && form.PICTURE">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="picture"
                accept="image/png, image/jpeg, image/jpg"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="pictureUploadBefore"
                :on-success="pictureUploadSuccess"
                :file-list="pictureList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.PICTURE) != '[]'">
              <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="form.PICTURE" @click="openPreview(0, form.PICTURE)"></el-image>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.PICTURE)">下载</el-button>
            </div>
          </template>
          <template slot="INSPECTION">
            <div v-if="dialogTitle != '详情' && form.INSPECTION">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="text"
                accept=".doc,.docx,.pdf"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="textUploadBefore"
                :on-success="inspectionUploadSuccess"
                :file-list="inspectionList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.INSPECTION) != '[]'">
              <div>{{ form.INSPECTIONNAME }}</div>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.INSPECTION)">下载</el-button>
            </div>
          </template>
          <template slot="CERT">
            <div v-if="dialogTitle != '详情' && form.CERT">
              <el-upload
                class="upload-demo"
                action="/api/blade-resource/oss/endpoint/put-file-attach"
                list-type="text"
                accept=".doc,.docx,.pdf"
                :on-change="changeFile"
                :headers="headersObj"
                :before-upload="textUploadBefore"
                :on-success="certUploadSuccess"
                :file-list="certList"
              >
                <el-button size="small" type="primary">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
              </el-upload>
            </div>
            <div v-if="dialogTitle === '详情' && JSON.stringify(form.CERT) != '[]'">
              <div>{{ form.CERTNAME }}</div>
              <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.CERT)">下载</el-button>
            </div>
          </template>
        </avue-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="handleCancel">取 消</el-button>
        <el-button v-if="dialogTitle !== '详情'" size="small" type="primary" @click="$refs.formRef.submit()">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      ref="transferDialog"
      class="tranfer-dialog"
      title="选择物料类别"
      width="60%"
      top="2vh"
      append-to-body
      :visible.sync="transferDialog"
      :close-on-click-modal="false"
      destroy-on-close=""
    >
      <div class="search-container" style="display: flex; flex-direction: row; width: 100%"></div>
      <el-row style="display: flex; flex-direction: row; width: 100%">
        <el-col :span="10">
          <avue-crud
            :key="timer"
            ref="leftCrud"
            :option="transferOption"
            :page.sync="leftPage"
            :data="leftData"
            :table-loading="leftLoading"
            v-model="leftForm"
            @search-change="searchLeftChange"
            @selection-change="selectionLeftChange"
            @current-change="currentLeftChange"
            @size-change="sizeLeftChange"
            @on-load="onLeftLoad"
          >
            <template slot="menuLeft">
              <el-button type="text"><span class="title">物料列表：</span></el-button>
            </template>
          </avue-crud>
        </el-col>
        <el-col :span="4" class="btn-container">
          <div class="transfer-button">
            <el-button type="primary" icon="el-icon-arrow-left" :disabled="rightSelectionList.length <= 0" class="btn" @click="moveToLeft"></el-button>
            <el-button type="primary" icon="el-icon-arrow-right" :disabled="leftSelectionList.length <= 0" class="btn" @click="moveToRight"></el-button>
          </div>
        </el-col>

        <el-col :span="10">
          <avue-crud :key="timer + 10000" :option="transferRightOption" :data="rightData" ref="rightCrud" @selection-change="selectionRightChange">
            <template slot="menuLeft">
              <el-button type="text"><span class="title">已选中列表：</span></el-button>
            </template>
          </avue-crud>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" icon="el-icon-circle-plus-outline" @click="handlePartSubmit" :disabled="rightData.length === 0" v-preventReClick>确 认</el-button>
        <el-button size="small" icon="el-icon-circle-close" @click="transferDialog = false">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 工具履历-->
    <el-dialog
      v-if="detailDialog"
      class="used-detail"
      ref="dialog"
      title="工具履历"
      :destroy-on-close="true"
      top="5vh"
      append-to-body
      destroy-on-close
      :visible.sync="detailDialog"
      :close-on-click-modal="false"
      @close="handleCloseModel"
    >
      <avue-crud
        :key="timer"
        :option="detailOption"
        :page.sync="detailPage"
        :data="detailData"
        :table-loading="detailLoading"
        ref="leftCrud"
        @current-change="currentDetailChange"
        @size-change="sizeDetailChange"
        @on-load="onDetailLoad"
      >
      </avue-crud>
    </el-dialog>
    <export-comp
      ref="exportComp"
      page-api-url="mes-product/ems-equipment/page?equipmentType=TOOL&subType=TEST_RACK"
      :option="option"
      :page="page"
      :query="exportParams"
      file-name="测试架"
    >
    </export-comp>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows"></common-modal-template>
  </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import commonModalTemplate from '@/components/common-modal-template/common-modal-template';
import { getTransferOption, transferRightOption, detailOption } from '@/views/product/refactor/testStand';
import { Base64 } from 'js-base64';
import website from '@/config/website';
import { getToken } from '@/util/auth';
import exportComp from '@/components/export-comp';
import { getTestStandList, getTestRackDetail, add, enable, remove, getProductList, getDetail } from '@/api/quality/equipment';
import { filterEmptyValues } from '@/util/util';
export default {
  name: 'testStand', // 会渲染成传入的componentName
  components: {
    userTableConfig,
    commonModalTemplate,
    exportComp
  },
  mixins: [userConfig()],
  data() {
    return {
      form: {},
      tableForm: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      exportParams: {},
      detailDialog: false,
      detailOption,
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      detailData: [],
      detailLoading: false,
      selectionList: [],
      transferOption: getTransferOption(this),
      transferRightOption,
      dialogVisible: false,
      dialogTitle: '',
      data: [{}],
      option: {
        calcHeight: 30,
        tip: false,
        selection: true,
        searchShow: true,
        searchMenuSpan: 4,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        addBtn: false,
        indexLabel: '序号',
        columnBtn: false,
        menuWidth: 250,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            searchSpan: 5
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            searchSpan: 5
          },
          {
            label: '规格',
            prop: 'specification'
          },
          {
            label: '新增时间',
            prop: 'createTime'
          },
          {
            label: '版本',
            prop: 'version'
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '批次',
            prop: 'lotNo'
          },
          {
            label: '适用产品',
            prop: 'partNo',
            search: true,
            searchSpan: 5
          },
          {
            label: '状态',
            prop: 'status',
            searchSpan: 5,
            search: true,
            type: 'select',
            dicData: [
              { label: '报废', value: 7 },
              { label: '待领用', value: 1 },
              { label: '待采集', value: 3 },
              { label: '已采集', value: 4 },
              { label: '禁用', value: 6 }
            ]
          }
        ]
      },
      formOption: {
        labelWidth: 70,
        submitBtn: false,
        emptyBtn: false,
        group: [
          {
            label: '基础信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            span: 8,
            column: [
              {
                label: '编码',
                prop: 'code',
                span: 8,
                rules: [
                  {
                    required: true,
                    message: '请输入编码',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '名称',
                prop: 'name',
                span: 8,
                rules: [
                  {
                    required: true,
                    message: '请输入名称',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '规格',
                prop: 'specification',
                span: 8,
                rules: [
                  {
                    required: true,
                    message: '请输入规格',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '版本',
                prop: 'version',
                span: 8
              },
              {
                label: '型号',
                prop: 'model',
                span: 8
              },
              {
                label: '批次',
                prop: 'lotNo',
                span: 8
              },

              {
                label: '适用产品',
                prop: 'suitPartName',
                search: true,
                disabled: true,
                type: 'search',
                span: 8,
                appendClick: () => {
                  this.rightData =
                    this.form.emsEquipmentPartVoS && this.form.emsEquipmentPartVoS.length > 0
                      ? this.form.emsEquipmentPartVoS.map((item) => {
                          return {
                            ...item,
                            partModel: item.partModel,
                            categoryName: item.partCategoryName,
                            name: item.partName
                          };
                        })
                      : [];
                  this.transferDialog = true;
                  this.$nextTick(() => {
                    let searchEls = document.querySelectorAll('.tranfer-dialog .avue-crud__search');
                    let searchContainer = document.querySelector('.search-container');
                    searchEls.forEach((ele, index) => {
                      if (index === 0) {
                        searchContainer.append(ele);
                      } else {
                        ele.style.display = 'none';
                      }
                    });
                  });
                }
              },
              // {
              //   label: '适用产品',
              //   prop: 'model',
              //   type: 'search',
              //   appendClick: (val) => {},
              //   span: 8
              // },
              {
                label: '负责部门',
                prop: 'principalDeptId',
                type: 'select',
                span: 8,
                dicUrl: '/api/blade-system/dept/tree',
                props: {
                  label: 'title',
                  value: 'id'
                }
              },
              {
                label: '负责人员',
                prop: 'principalName',
                type: 'search',
                appendClick: () => {
                  this.openUserModal();
                },
                disabled: true,
                span: 8
              },
              {
                label: '存储位置',
                prop: 'areaName',
                type: 'search',
                disabled: true,
                appendClick: (val) => {
                  this.openAreaCommonModal();
                },
                span: 8
              },
              {
                label: '备注',
                prop: 'remarks',
                type: 'textarea',
                span: 8
              }
            ]
          },
          {
            label: '购置信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            span: 8,
            column: [
              {
                label: '资产编码',
                prop: 'assetCode',
                span: 8
              },
              {
                label: '购置价格',
                prop: 'procurementPrice',
                span: 8,
                rules: [
                  {
                    required: false,
                    trigger: 'blur',
                    validator: (rule, value, callback) => {
                      let reg = /^((0{1}\.\d{1,4})|([0-9]\d*\.{1}\d{1,4})|([0-9]+\d*))$/g;
                      if (value && !reg.test(value)) {
                        callback(new Error('购置价格为数字，不能小于0，可保留4位小数'));
                      } else {
                        callback();
                      }
                    }
                  }
                ]
              },
              {
                label: '供应商',
                prop: 'supplierName',
                span: 8,
                type: 'search',
                disabled: true,
                appendClick: () => {
                  this.openPartnerCommonModal();
                }
              },
              {
                label: '购置日期',
                prop: 'procurementDate',
                span: 8,
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '入账日期',
                prop: 'acceptanceDate',
                span: 8,
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '出厂日期',
                prop: 'manufactureDate',
                span: 8,
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              },
              {
                label: '启用日期',
                prop: 'commissioningDate',
                span: 8,
                type: 'datetime',
                format: 'yyyy-MM-dd HH:mm:ss',
                valueFormat: 'yyyy-MM-dd HH:mm:ss'
              }
            ]
          },
          {
            label: '附件信息',
            prop: 'equipmentInfo',
            collapse: true,
            icon: 'el-icon-vertical-bar',
            labelWidth: 100,
            column: [
              {
                label: '设备图片',
                prop: 'PICTURE',
                span: 8,
                type: 'upload'
              },
              {
                label: '验收报告附件',
                prop: 'INSPECTION',
                span: 8,
                type: 'upload'
              },
              {
                label: '投产验证附件',
                prop: 'CERT',
                span: 8,
                type: 'upload'
              }
            ]
          }
        ]
      },
      tableOption: {},
      leftSelectionList: [],
      rightSelectionList: [],
      timer: new Date().getTime(),
      leftPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pagerCount: 3
      },
      leftData: [],
      leftLoading: false,
      leftForm: {},
      rightData: [],
      transferDialog: false,
      pictureList: [],
      inspectionList: [],
      certList: [],
      modalName: ''
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.testStand_add, false),
        viewBtn: this.vaildData(this.permission.testStand_view, false),
        delBtn: this.vaildData(this.permission.testStand_delete, false),
        editBtn: this.vaildData(this.permission.testStand_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    }
  },
  methods: {
    rowSave(row, done, loading) {},
    rowUpdate(row, index, done, loading) {},
    rowDel(row) {},
    beforeOpen(done, type) {},
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    async onLoad(page, params = {}) {
      this.loading = true;
      try {
        const res = await getTestStandList(page.currentPage, page.pageSize, Object.assign(params, this.query));
        const data = res.data.data;
        this.data = data.records;
        this.page.total = data.total;
        this.page.currentPage = data.current;
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    currentLeftChange(currentPage) {
      this.leftPage.currentPage = currentPage;
      this.onLeftLoad(this.leftPage);
    },
    sizeLeftChange(pageSize) {
      this.leftPage.pageSize = pageSize;
      this.onLeftLoad(this.leftPage);
    },
    searchLeftChange(params, done) {
      this.page.currentPage = 1;
      this.onLeftLoad(this.leftPage, params);
      done();
    },
    currentDetailChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      // this.onDetailLoad(this.detailPage);
    },
    sizeDetailChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      // this.onDetailLoad(this.detailPage);
    },
    onDetailLoad(page) {
      try {
        const params = { toolId: this.tableForm.id };
        this.detailLoading = true;
        getTestRackDetail(page.currentPage, page.pageSize, Object.assign(params))
          .then((res) => {
            const data = res.data.data;
            this.detailPage.total = data.total;
            if (data.records && data.records.length > 0) {
              this.detailData = data.records.map((item) => {
                return {
                  ...item,
                  ...JSON.parse(item.options)
                };
              });
            } else {
              this.detailData = [];
            }
          })
          .catch((e) => {
            console.log(e);
          })
          .finally(() => {
            this.detailLoading = false;
          });
      } catch (e) {
        console.log(e);
      }
    },
    selectionLeftChange(list) {
      this.leftSelectionList = list;
    },
    selectionRightChange(list) {
      this.rightSelectionList = list;
    },
    onLeftLoad(page, params = {}) {
      this.leftLoading = true;
      getProductList(page.currentPage, page.pageSize, Object.assign(params)).then((res) => {
        const data = res.data.data;
        this.leftPage.total = data.total;
        this.leftData = data.records;
        console.log(this.rightData);
        // this.rightData = this.handleRightData(this.leftData, this.form.equipmentPartList);
        this.leftLoading = false;
        if (this.rightData.length) {
          this.$refs.leftCrud.toggleSelection(this.rightData);
        }
      });
    },
    handlePartSubmit() {
      this.form.equipmentPartList = this._map(this.rightData, (item) => {
        return {
          partMasterId: item.id,
          partNo: item.partNo,
          partName: item.name
        };
      });
      this.form.suitPartName = String(this._map(this.rightData, (item) => item.name));
      this.transferDialog = false;
    },
    selectionLeftRightClear() {
      this.leftSelectionList = [];
      this.rightSelectionList = [];
    },
    /*
     * 移至左边
     */
    moveToLeft() {
      this.rightData = this._differenceWith(this.rightData, this.rightSelectionList, (item1, item2) => {
        return item1.name === item2.name && item1.partNo === item2.partNo;
      });
    },
    /*
     * 移至右边
     */
    moveToRight() {
      this.rightData = this._unionBy(this.rightData, this.leftSelectionList, 'partNo');
      this.rightSelectionList = [];
      this.$refs.rightCrud.refreshTable();
    },
    changeFile(files, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    pictureUploadBefore(file) {
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        return false;
      }
    },
    pictureUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('PICTURE' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.PICTURE = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'PICTURE'
      });
    },
    inspectionUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('INSPECTION' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.INSPECTION = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'INSPECTION'
      });
    },
    certUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('CERT' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.CERT = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'CERT'
      });
    },
    textUploadBefore(file) {
      if (file.name.split('.')[1] != 'doc' && file.name.split('.')[1] != 'docx' && file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传dox/docx/pdf文件！'
        });
        return false;
      }
    },
    handleViewHistory(row) {
      this.tableForm.id = row.id;
      this.detailDialog = true;
    },
    handleDisabled(row) {
      this.$confirm(`是否确定${row.status === 6 ? '启用' : '禁用'}这条数据?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        enable({
          id: row.id,
          // 禁用 传6 启用传 1
          status: row.status === 6 ? 1 : 6
        }).then(
          () => {
            this.onLoad(this.page);
            this.$message({
              type: 'success',
              message: '操作成功!'
            });
          },
          (error) => {}
        );
      });
    },
    async handleEdit(row) {
      await getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.handleDetailData(data);
      });
      this.$set(this.formOption, 'detail', false);
      this.dialogTitle = '编辑';
      this.dialogVisible = true;
    },
    handleDetailData(data) {
      this.form = data;
      let versionJson = typeof this.form.extFields === 'string' ? JSON.parse(this.form.extFields) : { version: '' };
      this.form.version = versionJson.version;
      this.form.suitPartName = String(this._map(data.emsEquipmentPartVoS || [], (item) => item.partName));
      data.equipmentAttachmentList = this._map(data.equipmentAttachmentList || [], (item) => {
        return {
          ...item,
          name: item.originalName,
          url: item.link
        };
      });
      this.pictureList = this._filter(data.equipmentAttachmentList || [], (item) => item.attachmentType === 'PICTURE');
      this.inspectionList = this._filter(data.equipmentAttachmentList || [], (item) => item.attachmentType === 'INSPECTION');
      this.certList = this._filter(data.equipmentAttachmentList || [], (item) => item.attachmentType === 'CERT');
      this._forEach(data.equipmentAttachmentList, (item) => {
        if (item.attachmentType === 'PICTURE') {
          this.form.PICTURE = item.link;
        } else if (item.attachmentType === 'INSPECTION') {
          this.form.INSPECTION = item.link;
          this.form.INSPECTIONNAME = item.originalName;
        } else if (item.attachmentType === 'CERT') {
          this.form.CERT = item.link;
          this.form.CERTNAME = item.originalName;
        }
      });
    },
    async handleView(row) {
      await getDetail(row.id).then((res) => {
        let data = res.data.data;
        this.handleDetailData(data);
      });
      this.$set(this.formOption, 'detail', true);
      this.dialogTitle = '详情';
      this.dialogVisible = true;
    },
    handleDel() {
      const canDelete = this.selectionList.every((item) => [6, 7].includes(item.status));
      if (!canDelete) {
        this.$message({
          type: 'warning',
          message: `只有禁用和报废状态的工具能删除`
        });
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    async handleAdd() {
      // await this.getDetail(row.id);
      this.$set(this.formOption, 'detail', false);
      this.dialogTitle = '新增';
      this.dialogVisible = true;
    },
    getDetail(id) {},
    handleCancel() {
      this.$refs.formRef.resetForm();
      this.dialogVisible = false;
    },
    submitForm(form, done) {
      try {
        delete form.PICTURE;
        delete form.INSPECTION;
        delete form.CERT;
        form.equipmentType = 'TOOL';
        form.subType = 'TEST_RACK';
        form.extFields = JSON.stringify({ version: this.form.version });
        add(form).then((res) => {
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.$refs.formRef.resetFields();
          this.onLoad(this.page);
          this.dialogVisible = false;
        });
      } catch (e) {
        console.warn(e);
      }
      done();
    },
    /**
     * 打开客户信息模态框
     */
    openPartnerCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'customModel';
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 用户信息模态框
     */
    openUserModal() {
      this.modalName = 'userModel';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'name',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },

    openAreaCommonModal() {
      this.modalName = 'areaModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择存储位置（双击进行选择）',
        url: '/api/mes-admin/area/page/storage/management',
        isPage: true,
        lazy: true,
        index: false,
        query: {
          parentId: 0
        },
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '名称',
            prop: 'name',
            labelWidth: 150,
            search: true,
            order: 1
          },
          {
            label: '编码',
            prop: 'code',
            labelWidth: 150,
            search: true,
            order: 2
          },
          {
            label: '仓库类型',
            prop: 'inventoryType',
            type: 'select',
            order: 3,
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            dicUrl: '/api/blade-system/dict/dictionary?code=inventory_type'
          },
          {
            label: '储位类型',
            labelWidth: 150,
            prop: 'areaTypeName'
          },
          {
            label: '备注',
            order: 13,
            labelWidth: 150,
            prop: 'remark'
          }
        ]
      };
    },
    handleExport() {
      this.exportParams = filterEmptyValues(this.query);
      this.$refs.exportComp.visible = true;
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handleCloseModel() {
      console.log(11);
      this.detailPage = {
        pageSize: 20,
        currentPage: 1,
        total: 0
      };
    },
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'customModel':
          this.form.partnerId = this._get(rowData, 'id', '');
          this.form.supplierName = this._get(rowData, 'name', '');
          break;
        case 'userModel':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'realName', '');
          break;
        case 'areaModal':
          if (rowData.areaType !== 'STORAGE') {
            this.$message({
              type: 'warning',
              message: '存储位置应选择对应储位，请选择对应储位'
            });
            return;
          }
          this.form.areaName = this._get(rowData, 'name', '');
          this.form.areaCode = this._get(rowData, 'code', '');
          this.form.areaId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
.tranfer-dialog {
  ::v-deep .avue-crud__search {
    width: 100% !important;
    border: none !important;
  }
  ::v-deep .avue-crud__right {
    display: none !important;
  }
  .btn-container {
    .transfer-button {
      height: 100%;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }

    .btn {
      margin: 20px 0;
    }
    .el-button + .el-button {
      margin-left: 0;
    }
  }
}
.used-detail {
  ::v-deep .avue-crud__menu {
    display: none;
  }
}
</style>
